﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO;
using System.Net.Mail;

using System.Configuration;
using System.Xml;

using E.Web.UI.Page;
using E.BLL;

using X.Common;
using E.Model;

namespace E.Web.Teacher
{
    public class Global : System.Web.HttpApplication
    {
        public int mailDay;
        public string mailTime;
        public string mailName;
        public string mailPass;
        public string mailHost;
        public string mailTitle;
        public string mailContent;
        XmlDocument xDoc = new XmlDocument();
        protected void Application_Start(object sender, EventArgs e)
        {
            string strMailDay = "";
            string filepath = System.AppDomain.CurrentDomain.BaseDirectory + "Mail\\MailConfig.xml";
            xDoc.Load(filepath);
            
            if (xDoc != null)
            {
                XmlNodeList xNodeList = xDoc.SelectNodes(".//root/mail");
                foreach (XmlElement el in xNodeList)
                {
                    XmlAttributeCollection xmlAttrList = el.Attributes;
                    if (xmlAttrList[0].Value == "mailday")
                        strMailDay = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailtime")
                        mailTime = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailname")
                        mailName = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailpass")
                        mailPass = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailhost")
                        mailHost = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailtitle")
                        mailTitle = xmlAttrList[1].Value;
                    if (xmlAttrList[0].Value == "mailcontent")
                        mailContent = xmlAttrList[1].Value;
                }
            }
            mailDay = Int32.Parse(strMailDay);
            //设置时间间隔
            //System.Timers.Timer MT = new System.Timers.Timer(mailDay * 24 * 60 * 60 * 1000);
            System.Timers.Timer MT = new System.Timers.Timer(20 * 1000);
            MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);
            MT.Enabled = true;

        }
        //构造System.Timers.Timer实例   间隔时间事件  (定时执行事件) 
        private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            bool isOpenSendMail = false;
            //开始工作
            string filepath = System.AppDomain.CurrentDomain.BaseDirectory + "Mail\\MailConfig.xml";
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(filepath);

            if (xDoc != null)
            {
                XmlNodeList xNodeList = xDoc.SelectNodes(".//root/switch");
                XmlNode node = xNodeList.Item(0);
                if (node.Attributes[0].Value == "isopen")
                {
                    isOpenSendMail = bool.Parse(node.Attributes[1].Value);
                }
            }
            if (isOpenSendMail)
            {
                StartWork();
            }
        }

        public void StartWork()
        {
            DateTime dtNow = DateTime.Now;
            DateTime dtMail = Convert.ToDateTime(mailTime);
            UserBLL bll=new UserBLL();
            //时间比较
            if (dtNow.Subtract(dtMail).Days > mailDay)
            {
                IList<SearchStudyLogModel> lst = bll.GetUnfinishUserCourseEmail();
                foreach (SearchStudyLogModel model in lst)
                {
                    //发送邮件
                    bool iStatus = SendMail(model, mailTitle);
                    string filepath = System.AppDomain.CurrentDomain.BaseDirectory + "Mail\\maillog.txt";
                    if (iStatus)
                    {
                        using (StreamWriter sw = new StreamWriter(filepath, true, System.Text.Encoding.UTF8))
                        {
                            sw.Write(System.DateTime.Now.ToString() + " 发送邮件" + model.Email + "成功!\r\n");
                        }
                       
                    }
                    else
                    {
                        using (StreamWriter sw = new StreamWriter(filepath, true, System.Text.Encoding.UTF8))
                        {
                            sw.Write(System.DateTime.Now.ToString() + " 发送邮件" + model.Email + "失败!\r\n");
                        }
                    }
                }
            }
           
        }
        public bool SendMail(SearchStudyLogModel model, string sSubject)
        {

            string sRecipientEmail = model.Email;
            //邮件对象
            MailMessage emailMessage;

            //smtp客户端对象

            SmtpClient client;

            // 初始化邮件对象

            String sSenderEmail = mailName;
            string sMessage = mailContent.Replace("{UserName}", model.UserName).Replace("{CourseName}", model.CourseName);

            emailMessage = new MailMessage(sSenderEmail, sRecipientEmail, sSubject, sMessage);
            emailMessage.IsBodyHtml = true;
            emailMessage.SubjectEncoding = System.Text.Encoding.Default;
            emailMessage.BodyEncoding = System.Text.Encoding.Default;
            //加入
            emailMessage.Headers.Add("X-Priority", "3");
            emailMessage.Headers.Add("X-MSMail-Priority", "Normal");
            emailMessage.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            emailMessage.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");

            //邮件发送客户端
            client = new SmtpClient();

            //邮件服务器及帐户信息
            client.Host = mailHost;
            //client.Host = "smtp.163.com";

            //client.Port = 465;
            //client.EnableSsl = true;
            System.Net.NetworkCredential Credential = new System.Net.NetworkCredential();

            Credential.UserName = mailName;  //可以在资源文件中配置
            Credential.Password = mailPass;

            client.Credentials = Credential;

            try
            {
                client.Send(emailMessage);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            int userid = Utils.StrToInt(Utils.GetCookie("teacherid"), -1);
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}